/*p:app/js*/
/*f:conf/app.js*/
/*
runTime: 0.0049
fileTree:
 +---- conf/app.js
 |  +---- app/common/wlistener.js
 |  +---- app/common/menuEvent.js
 |  |  +---- app/common/getElement.js
 |  +---- app/common/request.js
 |  +---- app/mod/login.js
 |  +---- app/mod/appmenu.js
*/
/**
 * 进一步封装core.util.listener, 增加白名单策略, 避免在项目中, 广播混乱
* @author FlashSoft | fangchao@staff.sina.com.cn
* @changelog WK | wukan@ move to common folder
* @changelog Finrila | wangzheng4@ add data_cache_get 
 */
STK.register('wlistener', function($){
	var listenerList = {};
	var that = {};
	/**
	 * 创建广播白名单
	 * @param {String} sChannel
	 * @param {Array} aEventList
	 */
	that.define = function(sChannel, aEventList){
		if (listenerList[sChannel] != null) {
			throw 'common.listener.define: 频道已被占用';
		}
		listenerList[sChannel] = aEventList;
		
		var ret = {};
		ret.register = function(sEventType, fCallBack){
			if (listenerList[sChannel] == null) {
				throw 'common.listener.define: 频道未定义';
			}
			$.listener.register(sChannel, sEventType, fCallBack);
		};
		ret.fire = function(sEventType,oData){
			if (listenerList[sChannel] == null) {
				throw 'commonlistener.define: 频道未定义';
			}
			$.listener.fire(sChannel, sEventType, oData);
		};
		ret.remove = function(sEventType, fCallBack){
			$.listener.remove(sChannel, sEventType, fCallBack);
		};
		
		/**
		 * 使用者可以在任意时刻获取到listener缓存的(某频道+事件)最后一次触发(fire)的数据；如果没有fire过为undefined;
		 * @method cache 
		 * @param {String} sEventType
		 */
		ret.cache = function(sEventType){
			return $.listener.cache(sChannel, sEventType);
		};
		return ret;
	};
	return that;
});


STK.register('getElement',function($){
	return function(el, type, tagName){
		if(!el) return;
        if (tagName) {
            tagName = tagName.toUpperCase();
        }
        var node = el[type];
        while (node) {
            if (node.nodeType == 1 && (tagName ? node.nodeName == tagName : true)) {
                break;
            }
            node = node[type];
        }
        return node;
	};
});

STK.register('menuEvent',function($){
	/*
	 * spec = {
			region : 
			tag : 
			over :
			delay :
		}
	 */
	return function(spec){
		var delay = spec.delay || 500;
		var region = spec.region;
		var tag = spec.tag;
		var timeout = null;
		var selectNode = null;
		var hover = function(e){
			if (timeout) {
				clearTimeout(timeout);
				timeout = null;
			}
			var el = $.core.evt.fixEvent(e).target;
			if (el.nodeName !== tag) {
				el = $.getElement(el, "parentNode", tag);
			}
			if(el && !el.getAttribute("node-type")) return;
			if (selectNode) {
				selectNode.className = "";
				selectNode = null;
			}
			if (el) {
				selectNode = el;
				spec['over'] && spec['over'](el);
			}
		}

		var out = function(e){
			timeout = setTimeout(function () {
				if (selectNode) {
					selectNode.className = "";
					selectNode = null;
				}
			}, delay);
		}
				
		$.addEvent(region, 'mouseover', hover);
		$.addEvent(region, 'mouseout', out);
		
		var that = {};
		that.destroy = function() {
			$.removeEvent(region, 'mouseover', hover);
			$.removeEvent(region, 'mouseout', out);
		};
		return that;
	};
});
STK.register('request', function($){
    return function(spec){
        spec.method = spec.method || 'post';
        spec.timeout = spec.timeout || 10000;
        spec.cb = spec.cb ||
        function(){
        };
        spec.ecb = spec.ecb ||
        function(){
        };
        if (!spec.url) 
            return;
        spec.onComplete = function(json){
            if (json.code == "OK0000") {
                spec.cb();
                for (i in json.data) {
                    $.gListener && $.gListener.fire(i, json.data[i]);
                }
            }
        };
        spec.onFail = function(json){
            spec.ecb(json);
        };
        spec.onTimeout = spec.onFail;
        $.ajax(spec);
    };
});
STK.register('app.mod.login', function($){
    /*
     * spec = {
     region :
     tag :
     over :
     delay :
     }
     */
    return function(){
    
        var info = '<div class="errorLayer" node-type="tipBox" style="position: absolute; left: 938px;top: 113px; z-index: 1010; display:none; "><div class="mid"><div class="close" onclick="this.parentNode.style.display=\'none\';">x</div><div class="conn"><p class="bigtxt" id="mod_login_title">登录名或密码错误</p><span class="stxt" id="mod_login_content" style="padding:0px;"><p class="stxt2">1、登录名是邮箱地址的用户</p><p class="stxt">请输入：yourname@sina.com</p><p class="stxt2"> 2、手机通行证方式注册的用户</p><p class="stxt">请输入：yourname@3g.sina.cn</p><p class="stxt2"> 3、请检查登录名大小写是否正确</p><p class="stxt2"> 4、请检查密码大小写是否正确</p></span></div></div></div>';
        
        var LOGINBOXTEMPLATE = '<div node-type="loginBox"  class="login-container"><div class="login-form"><fieldset>\
		<label class="login" for="email">Email:</label><input class="text" id="email" name="email" type="text">\
		<p class="username-hint">ex: joe@example.com</p>\
		<label class="login" for="password">Password:</label><input class="text" id="password" name="password" type="password">\
		<p class="remember_me"><input id="remember_me" name="remember_me" type="checkbox" value="1">\
		<label class="text" for="remember_me">Stay signed in</label></p>\
		<p><a node-type="loginBtn" class="submit green awesome">Log in</a></p>\
		<div class="forgot-password"><a href="#" node-type="forgotBtn">Forgot your password?</a></div>\
		</fieldset></div>' + info + '</div>';
        
        var dom = $.builder(LOGINBOXTEMPLATE), lbox = dom.list['loginBox'][0], lbtn = dom.list['loginBtn'][0], fbtn = dom.list['forgotBtn'][0], tbox = dom.list['tipBox'][0], vr_email = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, vr_password = /[A-Za-z0-9]{1,20}$/;
        
        $.E('mainbox').appendChild(lbox);
        
        var loginEvent = function(){
            var json = $.htmlToJson(lbox, ["INPUT"], false);
            if (vr_email.test(json.email) && vr_password.test(json.password)) {
                json['func'] = 'login';
                $.request({
                    url: 'user.s',
                    args: json,
                    cb: function(){
                        tbox.style.display = "none";
                    }
                });
            }
            else {
                tbox.style.display = "";
            }
        };
        $.addEvent(lbtn, 'click', loginEvent);
        //			$.addEvent(fbtn, 'click', function(){});
        
        $.gListener.register('login', function(){
            lbox.style.display = "none";
        });
        $.gListener.register('logout', function(){
            lbox.style.display = "";
        });
    };
});
STK.register('app.mod.appmenu', function($){
    return function(){
        var APPMENUTEMPLATE = '<div class="container" node-type="appmenu" style="display: none;"><div class="panel">\
									<div class="panel-header"><span>应用列表</span><a class="panel-header-button">X</a><a class="panel-header-button">[]</a><a class="panel-header-button">-</a></div>\
									<div class="panel-content"><div><ul node-type="applist"></ul></div></div>\
								</div></div>';
        var ICON = '<img src="http://ww4.sinaimg.cn/large/655d1835jw1djkhem105bj.jpg" width="80" class="fl"><button>添加</button>';
        var LITEMPLATE = '<li style="float: left;  width: 234px;  height: 60px;  padding: 6px 0 6px 6px;  border: 1px solid #ECECEC;  position: relative;  margin: 0 15px 15px 0;  overflow: hidden;">\
								<a href="http://game.weibo.com/home/game?appId=1319144208&amp;origin=1009" data="http://ww1.sinaimg.cn/large/70f6e843jw1djrdy0bx0vj.jpg&amp;+&amp;奔跑彩虹马&amp;+&amp;3&amp;+&amp;10&amp;+&amp;1319144208" c="3" class="img" style="float: left;  width: 60px;  height: 60px;  display: block;  margin-right: 10px;"><img src="http://weiyouxi-img.stor.appsina.com/029f822066c76b5e86ec6e22816418a7.png" width="60"></a>\
								<div class="fl" style="float: left;">\
									<p class="main-link" style="width: 154px;  height: 14px;  line-height: 14px;  _line-height: 16px;  margin-bottom: 9px;"><a href="http://game.weibo.com/home/game?appId=1319144208&amp;origin=1009" title="热身完毕" style="color: #0095CD;">热身完毕</a></p>\
									<p title="在游戏中得到5000分" class="all" style="height: 35px;  color: #666;  text-decoration: none;  cursor: default;  line-height: 18px;">在游戏中得到5000分</p>\
								</div>\
							</li>';
		var dom = $.builder(APPMENUTEMPLATE), appmenu = dom.list['appmenu'][0], applist = dom.list['applist'][0];
        $.E('mainbox').appendChild(appmenu);
        appmenu.style.display = "";
        $.request({
            url: 'app.s',
            args: {
                func: 'getams',
				uid:$.uid
            }
        });
        $.gListener.register('ams', function(list){
            var lit = $.C('li');
            for (var i = 0, len = list.length; i < len; i++) {
                var app = list[i];
                var li = lit.cloneNode();
                li.innerHTML = ICON;
                applist.appendChild(li);
            }
        });
        $.gListener.register('logout', function(){
            appmenu.style.display = "none";
        });
    };
});

STK.register('app.mod.tree', function($){
    return function(){
        var APPMENUTEMPLATE = '<div class="container" node-type="container" style="display: none;"><div class="panel">\
									<div class="panel-header"><span>树</span><a class="panel-header-button">X</a><a class="panel-header-button">[]</a><a class="panel-header-button">-</a></div>\
									<div class="panel-content"><div><ul node-type="region"></ul></div></div>\
								</div></div>';
		var dom = $.builder(APPMENUTEMPLATE), container = dom.list['container'][0], region = dom.list['region'][0];
        $.E('mainbox').appendChild(container);
        container.style.display = "";
		region.innerHTML = '';
		
		
    };
});

STK.pageletM.register('app.common.init', function($){
    $.gListener = $.wlistener.define('homer', ['login', 'logout']);
    $.thread = {};
    $.gListener.register('login', function(userinfo){
		if (userinfo) {
			var u = $.jsonToStr(userinfo);
			u && $.cookie.set('u', u);
			$.uid = userinfo.id;
		}
    });
    $.gListener.register('logout', function(){
		$.request({url:'user.s',args:{func:'logout'}});
        $.cookie.remove('u');
    });
});

STK.pageletM.register('app.header.init', function($){
    var selectNode = null;
    var timeout = null;
    var region = $.E('userbox');
    //	$.menuEvent({
    //		region:$.E('applist'),
    //		tag:'LI',
    //		over:function(el){el.className = "current";}
    //	});
    var showAccount = function(userinfo){
        if (userinfo) {
            region.innerHTML = '<ul class="person"><li><a action-type="logout" href="#" class="link">退出</a></li><li><a href="#" class="link">' + userinfo.username + '</a></li></ul>';
            var dEvt = $.delegatedEvent(region);
            dEvt.add('logout', 'click', function(e){
                $.gListener.fire('logout');
            });
        }
    };
    var showOnLogin = function(){
        region.innerHTML = '<p class="no_login"><span>= v = 还没有帐号的同学们先注册吧。</span><a href="/signup/signup.php?topnav">注册</a><em>|</em><a node-type="loginBtn" href="javascript:void(0)">登录</a></p>';
    };
    $.gListener.register('login', showAccount);
    $.gListener.register('logout', showOnLogin);
    showOnLogin();
});

STK.pageletM.register('app.main.init', function($){
    $.gListener.register('login', function(){
        $.app.mod.appmenu();
		$.app.mod.tree();
    });
    var userinfo = decodeURIComponent($.cookie.get('u'));
    if (userinfo) {
        userinfo = $.strToJson(userinfo);
        $.gListener.fire('login', userinfo);
    }
    else {
        $.app.mod.login();
    }
});
STK.pageletM.start();